﻿using FriendAnalyzer.Infrastructure.Facebook.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;

namespace FriendAnalyzer.Infrastructure.Files
{
    public class FileManager : FriendAnalyzer.Infrastructure.Files.IFileManager
    {
        public async Task DownloadFilesAsync(IEnumerable<FacebookUser> users)
        {
            foreach (var user in users)
            {
                await DownloadUserProfilePhoto(user);
            }
        }

        private async Task DownloadUserProfilePhoto(FacebookUser user)
        {
            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage(HttpMethod.Get, user.PictureUrl))
            using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead))
            {
                var fileName = string.Format("{0}.jpg", user.UserID);
                var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
                var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
                using (var writer = new DataWriter(fs.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
                    await writer.StoreAsync();
                    writer.DetachStream();
                }
                await fs.FlushAsync();
            }
        }

        public async Task<List<Tuple<string, BitmapImage>>> GetImagesAsync()
        {
            var files = await ApplicationData.Current.LocalFolder.GetFilesAsync();
            var result = new List<Tuple<string, BitmapImage>>();

            foreach (var file in files.Where(f => f.FileType.EndsWith("jpg")))
            {
                var image = new BitmapImage();

                await image.SetSourceAsync(await file.OpenReadAsync());

                result.Add(new Tuple<string, BitmapImage>(Path.GetFileNameWithoutExtension(file.Name), image));
            }

            return result;
        }
    }
}